;
(function(factory) {
	layui.use(['layer', 'laypage', 'table', 'form', 'dropdown'], function() {
		factory(jQuery, window, document, layui);
	});
}(function($, window, document, layui) {
	$(function() {
		funOp.init();

		// funOp.addUser();
	});

	var funOp = {
		limit: 10,
		roleList: [],
		init: function() {

			$('#seach_submit').click(function() {
				funOp.queryUser(1);
				return false;
			});
			funOp.tableInit();

			funOp.add();
			// funOp.selectRole();

		},

		tableInit: function() {
			layui.table.render({
				toolbar: '#barDemo',
				toolbar: '#toolbarDemo',
				elem: '#user_table',
				limit: funOp.limit,
				cols: [
					[{
							fixed: 'right',
							title: '操作',
							toolbar: '#barDemo',
							width: 200
						},
						{
							field: 'id',
							title: 'ID',
							width: 60,
						}, {
							field: 'city',
							title: '区域',
							width: 150
						}, {
							field: 'userNo',
							title: '用户号',
							width: 150
						}, {
							field: 'idType',
							title: '证件类别',
							width: 150
						}, {
							field: 'idNum',
							title: '证件号码',
							width: 150
						}, {
							field: 'cardNo',
							title: '银行卡号',
							width: 150
						}
					]
				],
				data: []
			});
			layui.table.on('tool(user_table)', function(obj) {
				var data = obj.data; //获得当前行数据
				var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
				var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）

				if (layEvent === 'detail') {
					funOp.userDeatil(data);
				} else if (layEvent === 'del') {
					layer.confirm('确定删除这条数据吗', function(index) {
						// obj.del();
						layer.close(index);
						funOp.deleteUser(obj, data);
					});
				} else if (layEvent === 'edit') {
					//弹窗并赋值
					layer.open({
						type: 1,
						title: '修改用户',
						area: ['600px', '400px'],
						content: $('#forms').html()
					});
					var id = data.id;
					layui.form.val(
						"addOrUpdate_form", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
							"userNo": data.userNo // "name": "value"
								// ,"roleName": data.roleName
								// ,"telephone": data.telephone
								// ,"email": data.email
								,
							"city": data.city,
							"idType": data.idType,
							"idNum": data.idNum,
							"cardNo": data.cardNo,
							"delFlag": "0"
						});

					layui.form.on('submit(addOrUpdateSubmit)', function(data) {
						funOp.editUser(data.field, id);
						return false;
					});
				}
			});
		},
		tableReload: function(pageIndex, total, data) {
			layui.table.reload('user_table', {
				data: data
			});
			layui.laypage.render({
				elem: 'user_page',
				limit: funOp.limit,
				curr: pageIndex,
				groups: 2,
				count: total,
				layout: ['count', 'prev', 'page', 'next'],
				jump: function(obj, first) {
					if (!first) {
						funOp.queryUser(obj.curr);
					}
				}
			});

		},

		add: function() {
			layui.table.on('toolbar(user_table)', function(obj) {
				console.info(obj);
				//var checkStatus = table.checkStatus(obj.config.id);
				switch (obj.event) {
					case 'add':
						//layer.msg('添加');
						//打开新增弹窗;	
						layer.open({
							type: 1,
							title: '新增用户',
							area: ['600px', '400px'],
							content: $('#forms').html()
						});
						//layui.form.render();
						//layui.form.render(null, 'addOrUpdate_form');
						layui.form.on('submit(addOrUpdateSubmit)', function(data) {
							funOp.addUser(data.field);
							//console.log(data)
							//console.log(layui.form.val('addOrUpdate_form')); //被执行事件的元素DOM对象，一般为button对象
							//console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
							//console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
							return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
						});
						layui.form.render('select');
						break;
				};
			});

		},

		queryUser: function(pageIndex) {
			var params = layui.form.val('seach_form');
			var where = ' where 0=0 ';
			var paramList = [];
			var pageParamList = [];
			$.each(params, function(key, value) {
				if (!value || value == '') {
					return true;
				}
				where += ' and ' + key + ' like concat("%", ? ,"%")';
				paramList.push(value);
			})
			where += ' and del_flag=0';
			pageParamList = paramList.concat([(pageIndex - 1) * funOp.limit, (pageIndex) * funOp
				.limit
			]);

			var c = 'SELECT count(0) num from jsdf_qy ' + where;
			var s = 'SELECT * from jsdf_qy ' +
				where + ' limit !,! ';

			var cObj = {
				sql: $.fn.commUtil.getSqlStr(c, paramList)
			}
			var sObj = {
				sql: $.fn.commUtil.getSqlStr(s, pageParamList)
			}
			$.newAjax({
				url: $.fn.commUtil.constant.baseUrl + '/dealSql',
				data: JSON.stringify(cObj),
				success: function(res) {
					console.info(res)
					if (res.code != 0 || res.data.length == 0 || res.data[0] == 0) {
						alert(res.msg);
						return;
					}
					var total = res.data[0].num;
					$.newAjax({
						url: $.fn.commUtil.constant.baseUrl + '/dealSql',
						data: JSON.stringify(sObj),
						success: function(res) {
							console.info(res)
							if (res.code != 0) {
								alert(res.msg);
								return;
							}
							funOp.tableReload(pageIndex, total, res.data);
						}
					});
				}
			});
		},
		userDeatil: function(data) {
			//弹窗并赋值
			layer.open({
				type: 1,
				title: '查看用户',
				area: ['600px', '400px'],
				content: $('#queForm').html()
			});
			layui.form.val("formTest", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
				"city": data.city // "name": "value"
					,
				"userno": data.userNo,
				"idtype": data.idType,
				"idnum": data.idNum,
				"cardno": data.cardNo
			});
		},

		addUser: function(data) {
			var paramList = [];
			var s = 'insert into jsdf_qy ( ';
			$.each(data, function(key, value) {
				if (!value || value == '') {
					return true;
				}
				s += key + ',';
				paramList.push(value);
			})
			s += ' del_flag) values (?,?,?,?,?,?)'
			paramList.push(0);
			var sObj = {
				sql: $.fn.commUtil.getSqlStr(s, paramList)
			}
			$.newAjax({
				url: $.fn.commUtil.constant.baseUrl + '/dealSql',
				data: JSON.stringify(sObj),
				success: function(res) {
					// console.info(res)
					if (res.code != 0) {
						layer.msg('签约失败' + res.msg);
						return;
					} else {
						layer.close(layer.index);
						layer.msg('签约成功');
						funOp.queryUser(1);
					}

				}
			});
		},

		editUser: function(data, id) {
			var paramList = [];
			var s = 'update jsdf_qy set  ';
			$.each(data, function(key, value) {
				if (!value || value == '') {
					return true;
				}
				s += key + '= ?,';
				paramList.push(value);
			});
			//去除最后一个逗号 
			s = s.substring(0, s.length - 1);
			s += 'where id =' + id;
			var sObj = {
				sql: $.fn.commUtil.getSqlStr(s, paramList)
			}
			$.newAjax({
				url: $.fn.commUtil.constant.baseUrl + '/dealSql',
				data: JSON.stringify(sObj),
				success: function(res) {
					console.info(res)
					if (res.code != 0) {
						layer.msg('编辑失败' + res.msg);
						return;
					} else {
						layer.close(layer.index);
						layer.msg('编辑成功');
						funOp.queryUser(1);

					}

				}
			});
		},

		deleteUser: function(obj, dat) {
			var paramList = [];
			paramList.push(dat.id);
			//sql
			var delSql = 'update jsdf_qy set del_flag=1 where id=?';
			var delRes = {
				sql: $.fn.commUtil.getSqlStr(delSql, paramList)
			}
			$.newAjax({
				url: $.fn.commUtil.constant.baseUrl + '/dealSql',
				data: JSON.stringify(delRes),
				success: function(res) {
					console.info(res)
					if (res.code != 0) {
						layer.msg('删除失败' + res.msg);
						return;
					} else {
						layer.close(layer.index);
						layer.msg('删除成功');
						funOp.queryUser(1);
					}
				}
			});

			obj.del();
		},
		// selectRole: function() {
		// 	var Sql = 'select id,`city` ,user_no,id_type,id_num,card_no from jsdf_qy where del_flag=0 ';
		// 	var Res = {
		// 		sql: $.fn.commUtil.getSqlStr(Sql)
		// 	}
		// 	$.newAjax({
		// 		url: $.fn.commUtil.constant.baseUrl + '/dealSql',
		// 		data: JSON.stringify(Res),
		// 		success: function(res) {
		// 			console.info(res)
		// 			if (res.code != 0) {
		// 				layer.msg(res.msg);
		// 				return;
		// 			};
		// 			// $.each(res.data, function(i, n) {
		// 			// 	$("#queryRole").append("<option value='" + n.id + "'>" + n
		// 			// 		.roleName + "</option>");
		// 			// })
		// 		}
		// 	});
		// }
	};
}));
